package cn.example.smartagriculture.slice;

import cn.example.smartagriculture.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;

import java.util.Timer;
import java.util.TimerTask;

public class SplashAbilitySlice extends AbilitySlice {
    private int seconds = 6;
    private Timer timer = null;
    private Text txtSeconds, txtCancel;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_splash);
        txtSeconds = (Text)findComponentById(ResourceTable.Id_txtSeconds);
        txtCancel = (Text)findComponentById(ResourceTable.Id_txtCancel);
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                String strTime = String.format("%d" + "s", seconds);
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        txtSeconds.setText(strTime);
                    }
                });
                if(--seconds == 0) {
                    timer.cancel();
                    goToLogin();
                }
            }
        };
        timer.schedule(timerTask, 0, 1000);
        txtCancel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                timer.cancel();
                goToLogin();
            }
        });
    }

    private void goToLogin() {
        Intent intent = new Intent();
        present(new LoginAbilitySlice(), intent);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
